package com.Rsoft.goodWebsocketMan.handler;

import com.Rsoft.goodWebsocketMan.ui.listener.func.WebSocketListener;
import org.glassfish.tyrus.core.TyrusSession;

import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;

@ServerEndpoint("/ws")
public class MyServerHandler {

    @OnMessage
    public void onMsg(String msg, Session session) {
        TyrusSession tyrusSession = (TyrusSession) session;
        System.out.println(msg);
        String name = WebSocketListener.idNameHashMap.get(session.getId());
        WebSocketListener.serverRecvText("[ " + name + "] : " + msg);
    }

    @OnClose
    public void onClose(Session session) {
        System.out.println("close");
        TyrusSession tyrusSession = (TyrusSession) session;
        String name = WebSocketListener.idNameHashMap.get(tyrusSession.getId());
        WebSocketListener.delConnectList(name);
        WebSocketListener.idNameHashMap.remove(tyrusSession.getId());
        WebSocketListener.delSession(name);
    }

    @OnError
    public void onError(Session session, Throwable throwable) {
        System.out.println("error : " + throwable.getMessage());
    }

    @OnOpen
    public void onOpen(Session session) {
        System.out.println("open " + session.getId());
        TyrusSession tyrusSession = (TyrusSession) session;
        String name = WebSocketListener.connectCount.addAndGet(1) + "-" + tyrusSession.getRemoteAddr();
        WebSocketListener.idNameHashMap.put(tyrusSession.getId(), name);
        WebSocketListener.addSession(name, tyrusSession);
//        WebSocketListener.addSession(name,tyrusSession);
        WebSocketListener.addConnectList(name);
    }
}
